/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.dx.financehy.utils;

import cn.hutool.core.util.ObjectUtil;
import com.dx.financehy.exception.BadRequestException;
import org.hibernate.validator.internal.constraintvalidators.bv.EmailValidator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 验证工具
 * @author Zheng Jie
 * @date 2018-11-23
 */
public class ValidationUtil{

    /*
     * 2019最新
     *
     * 移动号码包括的号段：134/135/136/137,138,139；
     *                     147/148(物联卡号)；
     *                     150/151/152/157/158/159；
     *                     165（虚拟运营商）；
     *                     1703/1705/1706（虚拟运营商）、178；
     *                     182/183/184/187/188
     *                     198

     * 联通号段包括：130/131
     *               145
     *               155/156
     *               166/167(虚拟运营商)
     *               1704/1707/1708/1709、171
     *               186/186
     *
     * 电信号段包括： 133
     *                153
     *                162(虚拟运营商)
     *                1700/1701/1702(虚拟运营商)
     *                180/181/189
     *                191/199
     * */
    private static String REGEX_MOBILE = "^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$";

    private static Pattern P = Pattern.compile(REGEX_MOBILE);

    /**
     * 验证空
     */
    public static void isNull(Object obj, String entity, String parameter , Object value){
        if(ObjectUtil.isNull(obj)){
            String msg = entity + " 不存在: "+ parameter +" is "+ value;
            throw new BadRequestException(msg);
        }
    }

    /**
     * 验证是否为邮箱
     */
    public static boolean isEmail(String email) {
        return new EmailValidator().isValid(email, null);
    }

    /**
     * 校验手机号
     *
     * @param phone
     * @return
     */
    public static boolean isPhone(String phone) {
        if (phone == null || phone.length() != 11) {
            return Boolean.FALSE;
        }

        Matcher m = P.matcher(phone);
        return m.matches();
    }

}
